new Vue({
    el: '#app',
    data: {
        userInfo: {
            userName: '',
            roleId: ''
        },
        stats: {
            total: 0,
            normal: 0,
            vip: 0,
            temp: 0
        },
        userCars: [],
        searchKey: '',
        showModal: false,
        isEdit: false,
        form: {
            carId: '',
            userId: '',
            carNumber: '',
            carBrand: '',
            carModel: '',
            carColor: '',
            carType: '1',
            status: '0',
            seatNum:''
        },
        availableSeats: []
    },
    created() {
        this.loadUserInfo();
        this.loadUserCars();
        this.loadAvailableSeats();
    },
    methods: {
        // 加载用户信息
        loadUserInfo() {
            axios.get('../../userInfo')
                .then(response => {
                    if (response.data.success) {
                        this.userInfo = response.data.data;
                    }
                })
                .catch(error => {
                    console.error('Error loading user info:', error);
                });
        },

        // 加载车辆列表
        loadUserCars() {
            axios.get('/Parks/userCar/getAll')
                .then(response => {
                    if (response.data.code === 0) {
                        this.userCars = response.data.data;
                        this.calculateStats(response.data.data);
                    } else {
                        alert(response.data.msg || '加载车辆失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载车辆失败');
                });
        },

        // 计算统计数据
        calculateStats(cars) {
            this.stats.total = cars.length;
            this.stats.normal = cars.filter(car => car.carType === 1).length;
            this.stats.vip = cars.filter(car => car.carType === 2).length;
            this.stats.temp = cars.filter(car => car.carType === 3).length;
        },

        // 显示添加表单
        showAddForm() {
            this.isEdit = false;
            this.form = {
                userId: '',
                carId: '',
                carNumber: '',
                carBrand: '',
                carModel: '',
                carColor: '',
                seatNum: this.availableSeats[0].seatNum,
                carType: '1',
                status: '0'
            };
            this.showModal = true;
        },

        // 显示编辑表单
        showEditForm(car) {
            this.isEdit = true;
            this.form = { ...car };
            this.showModal = true;
        },

        // 关闭模态框
        closeModal() {
            this.showModal = false;
            this.form = {
                userId: '',
                carId: '',
                carNumber: '',
                carBrand: '',
                carModel: '',
                carColor: '',
                seatNum: '',
                carType: '1',
                status: '0'
            };
        },

        // 提交表单
        submitForm() {
            const url = this.isEdit ? 
                '/Parks/userCar/update' : 
                '/Parks/userCar/insert';
            
            // 确保数值类型正确
            this.form.carType = parseInt(this.form.carType);
            this.form.status = parseInt(this.form.status);
            
            axios.post(url, this.form)
                .then(response => {
                    if (response.data.code === 0) {
                        alert(this.isEdit ? '更新成功' : '添加成功');
                        this.closeModal();
                        this.loadUserCars();
                    } else {
                        alert(response.data.msg || (this.isEdit ? '更新失败' : '添加失败'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert(this.isEdit ? '更新失败' : '添加失败');
                });
        },

        // 删除车辆
        deleteCar(carId) {
            if (confirm('确定要删除这辆车吗？')) {
                axios.post('/Parks/userCar/deleteById', { carId })
                    .then(response => {
                        if (response.data.code === 0) {
                            alert('删除成功');
                            this.loadUserCars();
                        } else {
                            alert(response.data.msg || '删除失败');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('删除失败');
                    });
            }
        },

        handleSearch() {
            if (this.searchKey) {
                const results = this.userCars.filter(car =>  
                    car.carNumber && car.carNumber.includes(this.searchKey)
                );
        
                if( results.length === 0) {
                    alert("未找到该车辆");
                    return;
                }
                this.userCars = results; // 更新用户列表为搜索结果
            } else {
                this.loadUserCars(); // 如果没有搜索关键字，重新获取所有用户
            }
        },
        // 获取车辆类型文本
        getCarType(type) {
            const typeMap = {
                1: '固定车辆',
                2: 'VIP车辆',
                3: '临时车辆'
            };
            return typeMap[type] || '未知';
        },

        // 获取状态样式类
        getStatusClass(status) {
            const statusMap = {
                0: 'status-normal',
                1: 'status-disabled'
            };
            return statusMap[status] || '';
        },

        // 获取状态文本
        getStatusText(status) {
            const statusMap = {
                0: '正常',
                1: '禁用'
            };
            return statusMap[status] || '未知';
        },

        // 退出登录
        handleLogout() {
            axios.post('/Parks/logout')
                .then(() => {
                    sessionStorage.removeItem('userInfo');
                    window.location.href = '../../login.html';
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('退出失败');
                });
        },

        loadAvailableSeats() {
            axios.get('/Parks/parkingSeat/getAvailableSeats')
                .then(response => {
                    if (response.data.code === 0) {
                        this.availableSeats = response.data.data;
                        console.log(response.data.data + "空闲车位");
                    } else {
                        alert(response.data.msg || '加载空闲车位失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载空闲车位失败');
                });
        }
    }
}); 